package com.shen.nettysocketchat

import com.shen.library_nettysocket.IMSClientFactory.iMSClient
import com.shen.library_nettysocket.interf.IMSClientInterface
import com.shen.library_nettysocket.protobuf.MessageProtobuf.Msg
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import java.util.*

/**
 * 应用层的imsClient启动器
 */
class IMSClientBootstrap private constructor() {
    private var imsClient: IMSClientInterface? = null
    var isActive = false
        private set

    @Synchronized
    fun init(userId: String?, token: String?, hosts: String, appStatus: Int) {
        if (!isActive) {
            val serverUrlList = convertHosts(hosts)
            if (serverUrlList == null || serverUrlList.size == 0) {
                println("init IMLibClientBootstrap error,ims hosts is null")
                return
            }
            isActive = true
            println("init IMLibClientBootstrap, servers=$hosts")
            if (null != imsClient) {
                imsClient!!.close()
            }
            imsClient = iMSClient
            updateAppStatus(appStatus)
            imsClient!!.init(
                serverUrlList,
                IMSEventListener(userId!!, token!!),
                IMSConnectStatusListener()
            )
        }
    }

    /**
     * 发送消息
     *
     * @param msg
     */
    fun sendMessage(msg: Msg?) {
        if (isActive) {
            imsClient!!.sendMsg(msg)
        }
    }

    /**
     * 转换 Hosts
     * 将 [{"host":"192.168.10.170", "port":8866}, {"host":"192.168.10.171", "port":8877}]
     * 转成 列表
     */
    private fun convertHosts(hosts: String?): Vector<String?>? {
        if (!hosts.isNullOrEmpty()) {
            val hostArray = JSONArray.parseArray(hosts)

            if (null != hostArray && hostArray.size > 0) {
                val serverUrlList = Vector<String?>()
                var host: JSONObject
                for (i in hostArray.indices) {
                    host = JSON.parseObject(hostArray[i].toString())
                    serverUrlList.add(host.getString("host") + " " + host.getInteger("port"))
                }
                return serverUrlList
            }
        }
        return null
    }

    fun updateAppStatus(appStatus: Int) {
        imsClient?.setAppStatus(appStatus)
    }

    companion object {
        val instance = IMSClientBootstrap()
        @JvmStatic
        fun main(args: Array<String>) {
            val userId = "100001"
            val token = "token_$userId"
            val bootstrap = instance
            val hosts = "[{\"host\":\"127.0.0.1\", \"port\":8866}]"
            bootstrap.init(userId, token, hosts, 0)
        }
    }
}